package com.hj.aiagent.chatmemory;

import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄健
 */
@Component
public class RedissonChatMemory implements ChatMemory {

    private final RedissonClient redissonClient;

    // Redis Key 前缀（避免与其他业务 Key 冲突）
    private static final String CHAT_MEMORY_PREFIX = "chat:memory:";

    public RedissonChatMemory(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        RList<Message> messageList = getMessageList(conversationId);
        messageList.addAll(messages);
        // 可选：设置对话过期时间（如 24 小时后自动清除）
        // messageList.expire(24, java.util.concurrent.TimeUnit.HOURS);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        RList<Message> messageList = getMessageList(conversationId);
        int size = messageList.size();
        if (size <= 0) {
            return new ArrayList<>();
        }
        // 取最后 N 条消息（处理索引越界）
        int fromIndex = Math.max(0, size - lastN);
        return new ArrayList<>(messageList.subList(fromIndex, size));
    }

    @Override
    public void clear(String conversationId) {
        RList<Message> messageList = getMessageList(conversationId);
        messageList.clear();
    }

    // 获取（或创建）对话对应的分布式 List
    private RList<Message> getMessageList(String conversationId) {
        String redisKey = CHAT_MEMORY_PREFIX + conversationId;
        return redissonClient.getList(redisKey);
    }
}